package com.example.app1;

import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class LogUtil {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final BlockingQueue<String> queue = new LinkedBlockingQueue<>();

    private static String logDir;

    public static void setLogDir(String logDir1) {
        logDir = logDir1;
    }

    public static void info(String tag, String log) {
        info(tag, log, null);
    }

    public static void info(String tag, String log, Exception e) {
        log = sdf.format(new Date()) + "[" + tag + "]" + log;
        if (e != null) {
            Log.e(tag, log, e);
        } else {
            Log.d(tag, log);
        }

        StringBuilder sb = new StringBuilder(log);

        if (e != null) {
            sb.append("\n").append(e.getMessage());
            StackTraceElement[] stackTraces = e.getStackTrace();
            for (StackTraceElement stackTrace:stackTraces) {
                sb.append("\n").append(stackTrace.toString());
            }
        }
        try {
            queue.put(sb.toString());
            new Thread(new Runnable() {
                @Override
                public void run() {
                    writeLogToFile();
                }
            }).start();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

    }

    private synchronized static void writeLogToFile() {
        if (!queue.isEmpty()) {
            File logFile = new File(logDir, "app_log.txt");
            FileWriter fileWriter = null;
            try {
                if (logFile.exists()) {
                    fileWriter = new FileWriter(logFile, true);
                } else {
                    boolean newFile = logFile.createNewFile();
                    if (!newFile) {
                        Log.d("logFile", "create Log file Fail");
                        return;
                    }
                    fileWriter = new FileWriter(logFile);
                }

                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                while (!queue.isEmpty()) {
                    String log = queue.poll();
                    bufferedWriter.write(log);
                    bufferedWriter.newLine();
                }

                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
